import 'dart:async';

import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_detail_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_attention_widget/special_attention_staff_list_view.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_filter_button_widget.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/company_detail_by_type_list_view_model.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/widgets/company_detail_by_type_list_item_widget.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/edit_user_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_view_model.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_scroll_physics/vg_custom_bouncing_scroll.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'widgets/company_detail_by_type_list_filter_widget.dart';

/// 企业详情-根据类型显示列表
///
/// @author: zengxiangxi
/// @createTime: 1/11/21 10:52 AM
/// @specialDemand:
class CompanyDetailByTypeListWidget extends StatefulWidget {
  final GroupPersonCntBean groupInfoBean;

  final ValueNotifier<String> searchPageValueNotifier;


  final EdgeInsetsGeometry padding;
  final String currentCompanyId;

  const CompanyDetailByTypeListWidget(
      {Key key, this.currentCompanyId, this.groupInfoBean, this.searchPageValueNotifier, this.padding})
      : super(key: key);

  @override
  CompanyDetailByTypeListWidgetState createState() =>
      CompanyDetailByTypeListWidgetState();
}

class CompanyDetailByTypeListWidgetState extends BasePagerState<
        CompanyDetailByTypeListItemBean, CompanyDetailByTypeListWidget>
    with AutomaticKeepAliveClientMixin, VgPlaceHolderStatusMixin {
  CompanyDetailByTypeListViewModel _viewModel;

  StreamSubscription _streamSubscription;

  ValueNotifier<String> searchPageValueNotifier;

  CompanyDetailFilterNotification companyDetailFilterNotification;

  StreamSubscription eventStreamSubscription;
  StreamSubscription personDetailGroupRefreshEvent;
  // StreamSubscription streamSubscription;
  String _currentCompanyId;
  @override
  void initState() {
    super.initState();
    _currentCompanyId = widget?.currentCompanyId??"";
    searchPageValueNotifier = widget?.searchPageValueNotifier;
    _viewModel = CompanyDetailByTypeListViewModel(this, widget?.groupInfoBean,noNeedCache: searchPageValueNotifier!=null?false:null);
    _streamSubscription = CompanyDetailPageState.of(context)
        ?.refreshStreamController
        ?.stream
        ?.listen((companyId) {
      if (!UserRepository.getInstance().isLogined()) {
        return;
      }
      if(StringUtils.isNotEmpty(companyId) && companyId == _currentCompanyId){
        _viewModel?.refreshMultiPage();
      }
    });
    // streamSubscription = VgEventBus.global.on<CompanyDetailRefreshEvent>().listen((event) {
    //   _refreshSearch();
    //
    // });
    //先赋值
    searchPageValueNotifier?.addListener(_refreshSearch);
      companyDetailFilterNotification = CompanyDetailPageState.of(context)?.filterNotification;
      companyDetailFilterNotification?.companyDetailFilterValueNotifier?.addListener(_setFilterType);
    _refreshSearch();
    // 观察者模式,监听接口是否使用
    eventStreamSubscription =
        VgEventBus.global.on<MultiDelegeRefreshEvent>().listen((event) {
            _refreshSearch();
        });
    //观察者模式,监听接口是否使用
    personDetailGroupRefreshEvent =
        VgEventBus.global.on<PersonDetailGroupRefreshEvent>().listen((event) {
            _refreshSearch();
        });
  }

  void _setFilterType(){
    _refreshSearch();
  }

  void _refreshSearch() {
    // if (StringUtils.isEmpty(searchPageValueNotifier?.value)) {
    //   return;
    // }
    _viewModel?.refresh();
  }

  @override
  void dispose() {
    super.dispose();
    // streamSubscription.cancel();
    searchPageValueNotifier?.removeListener(_refreshSearch);
    _streamSubscription?.cancel();
    companyDetailFilterNotification?.companyDetailFilterValueNotifier?.removeListener(_setFilterType);
    eventStreamSubscription?.cancel();
    personDetailGroupRefreshEvent?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Column(
      children: <Widget>[
        SizedBox(height: 3),
        Expanded(
          child: MixinPlaceHolderStatusWidget(
              emptyOnClick: () => _viewModel?.refresh(),
              errorOnClick: () => _viewModel?.refresh(),
              child: _toListWidget()),
        ),
      ],
    );
  }

  Widget _toListWidget() {
    return VgPullRefreshWidget.bind(
      viewModel: _viewModel,
      state: this,
      child: ListView.separated(
          itemCount: data?.length ?? 0,
          padding: widget.padding ?? const EdgeInsets.only(bottom: 30),
          physics: VgBanPullBouncingScroll(),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          itemBuilder: (BuildContext context, int index) {
            return CompanyDetailByTypeListItemWidget(
              itemBean: data?.elementAt(index),
              onEdit: (CompanyDetailByTypeListItemBean itemBean) async {
                bool result = await EditUserPage.navigatorPush(context, itemBean?.fuid,itemBean?.fid);
                if(result ?? false){
                  _viewModel?.refreshMultiPage();
                }
                // bool result = await CompanyAddUserUpdateInfoPage.navigatorPush(
                //      context, itemBean?.fuid, itemBean?.fid,isDisableRole: _isDisableRoleEdit(itemBean));
                // if(result ?? false){
                //   _viewModel?.refreshMultiPage();
                // }
              },
              onRemove: (CompanyDetailByTypeListItemBean itemBean)async{
                bool result =
                    await CommonConfirmCancelDialog.navigatorPushDialog(context,
                    title: "提示",
                    content: "确定移除"+"${itemBean?.name??"该用户"}？",
                    cancelText: "取消",
                    confirmText: "移除",
                    confirmBgColor: ThemeRepository.getInstance()
                        .getMinorRedColor_F95355());
                if (result ?? false) {
                  _viewModel?.removeVeryCare(
                      context, itemBean?.fuid);
                }
              },
              onDelete: (CompanyDetailByTypeListItemBean itemBean) async {
                bool result =
                    await CommonConfirmCancelDialog.navigatorPushDialog(context,
                        title: "提示",
                        content: "确定删除"+"${itemBean?.name??"该用户"}？删除后不可恢复",
                        cancelText: "取消",
                        confirmText: "删除",
                        confirmBgColor: ThemeRepository.getInstance()
                            .getMinorRedColor_F95355());
                if (result ?? false) {
                  _viewModel?.deleteUserHttp(context,
                      fuid: itemBean?.fuid,
                      roleid: itemBean?.roleid,
                      userid: itemBean?.userid);
                }
              },
              onFaceIgnore: (CompanyDetailByTypeListItemBean itemBean) async {
                bool result =
                    await CommonConfirmCancelDialog.navigatorPushDialog(context,
                        title: "提示",
                        content: "确定忽略该用户？",
                        cancelText: "取消",
                        confirmText: "忽略",
                        confirmBgColor: ThemeRepository.getInstance()
                            .getMinorRedColor_F95355());
                if (result ?? false) {
                  _viewModel?.ignoreSingleFaceHttp(context, itemBean?.fid);
                }
              },
              onFaceDelete: (CompanyDetailByTypeListItemBean itemBean) async {
                bool result =
                    await CommonConfirmCancelDialog.navigatorPushDialog(context,
                        title: "提示",
                        content: "确定忽略该用户？",
                        cancelText: "取消",
                        confirmText: "忽略",
                        confirmBgColor: ThemeRepository.getInstance()
                            .getMinorRedColor_F95355());
                if (result ?? false) {
                  _viewModel?.deleteSingleFaceHttp(context, itemBean?.fid);
                }
              },
            );
          },
          separatorBuilder: (BuildContext context, int index) {
            return SizedBox(
              height: 0,
            );
          }),
    );
  }

  ///是否禁用身份修改
  bool _isDisableRoleEdit(CompanyDetailByTypeListItemBean itemBean) {
    if (itemBean == null ||
        StringUtils.isEmpty(itemBean?.userid) ||
        StringUtils.isEmpty(itemBean?.roleid)) {
      return false;
    }
    if (itemBean.userid ==
            UserRepository.getInstance().userData?.user?.userid &&
        VgRoleUtils.isSuperAdmin(itemBean.roleid)) {
      return true;
    }
    return false;
  }

  @override
  bool get wantKeepAlive => true;
}
